package com.jhgsys.internal.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.MD5Util;
import com.jhgsys.internal.system.dto.UserDto;
import com.jhgsys.internal.system.dto.UserSignInDto;
import com.jhgsys.internal.system.entity.Dept;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IDeptService;
import com.jhgsys.internal.system.service.ITenantService;
import com.jhgsys.internal.system.service.IUserService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author MrBird
 */
@Slf4j
@Validated
@RestController
@RequestMapping("user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IDeptService deptService;

    @Autowired
    private ITenantService tenantService;

    @GetMapping("{username}")
    public User getUser(@NotBlank(message = "{required}") @PathVariable String username) {
        return this.userService.findUserDetail(username);
    }

    @GetMapping("check/{username}")
    public boolean checkUserName(@NotBlank(message = "{required}") @PathVariable String username, String userId) {
        return this.userService.findByName(username) == null || StringUtils.isNotBlank(userId);
    }

    @GetMapping("list")
    @RequiresPermissions(value = {"user:view"}, logical = Logical.OR)
    public FebsResponse userList(User user, QueryRequest request) {
        if (!hasHeadCompanyRole()) {
            user.setTenantId(getCurrentTenantId());
        }
        Map<String, Object> dataTable = getDataTable(getUserIPage(user, request));
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping("mailList")
    @RequiresPermissions(value = {"ftamaillist:view"}, logical = Logical.OR)
    public FebsResponse userMailList(User user, QueryRequest request) {
        IPage<User> pageData = this.userService.findUserMail(user, request);
        Map<String, Object> dataTable = getDataTable(pageData);
        return new FebsResponse().success().data(dataTable);
    }

    private IPage<UserDto> getUserIPage(User user, QueryRequest request) {
        String currentUser = getCurrentUser().getUserName();
        IPage<UserDto> pageData = this.userService.findUserDetail(user, request);
        List<UserDto> userList = pageData.getRecords();
        if (userList != null && !userList.isEmpty()) {
            userList = userList.stream().filter(
                    u -> (!"sysadmin".equalsIgnoreCase(u.getUserName()))
            ).collect(Collectors.toList());
            pageData.setRecords(userList);
            pageData.setTotal(userList.size());
        }
        return pageData;
    }

    @Log("新增用户")
    @PostMapping
    @RequiresPermissions(value = {"user:add", "webuser:view", "ftauser:view"}, logical = Logical.OR)
    public FebsResponse addUser(@Valid User user) throws FebsException {
        try {
            if (StringUtils.isBlank(user.getTenantId())) {
                return new FebsResponse().fail().message("所属公司不能为空！");
            }
            User dbUser = this.userService.findByName(user.getUserName());
            if (dbUser != null) {
                return new FebsResponse().fail().message("用户名已经存在！");
            }
            //如果设置为部门领导人，则先修改原领导人状态
            if ("1".equals(user.getDeptLeaderFlg())) {
                User userLeader = this.userService.findLeaderByDeptId(user.getDeptId());
                if (null != userLeader) {
                    userLeader.setDeptLeaderFlg("0");
                    this.userService.updateById(userLeader);
                }
            }
            setDefaultDept(user);
            // 获取当前用户
            user.setCreatedBy(getCurrentUser().getUserName());
            this.userService.createUser(user);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增用户失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("删除用户")
    @GetMapping("delete/{userIds}")
    @RequiresPermissions(value = {"user:delete", "webuser:view", "ftauser:view"}, logical = Logical.OR)
    public FebsResponse deleteUsers(@NotBlank(message = "{required}") @PathVariable String userIds) throws FebsException {
        try {
            // 获取当前用户
            User user = new User();
            user.setDeletedBy(getCurrentUser().getUserName());
            user.setDeletedTime(new Date());
            user.setDeletedFlg(FebsConstant.INVALID);
            String[] ids = userIds.split(StringPool.COMMA);
            this.userService.updateUserDeletedFlg(ids, user);
            // this.userService.deleteUsers(ids);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除用户失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("修改用户")
    @PostMapping("update")
    @RequiresPermissions(value = {"user:update", "webuser:view", "ftauser:view"}, logical = Logical.OR)
    public FebsResponse updateUser(@Valid User user) throws FebsException {
        try {
            if (user.getUserId() == null) {
                return new FebsResponse().fail().message("用户ID为空");
            }
            User deptLeader = this.userService.findLeaderByDeptId(user.getDeptId());
            //如果设置成了部门负责人，则判断同部门下是否已经存在部门负责人
            if ("1".equals(user.getDeptLeaderFlg()) && null != deptLeader && !deptLeader.getUserId().equals(user.getUserId())) {
                if (null != deptLeader) {
                    deptLeader.setDeptLeaderFlg("0");
                    this.userService.updateById(deptLeader);
                }
            }
            setDefaultDept(user);
            // 获取当前用户
            user.setUpdatedBy(getCurrentUser().getUserName());
            this.userService.updateUser(user);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改用户失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("修改用户启用/停用状态")
    @PostMapping("updateStatus")
    @RequiresPermissions(value = {"user:update", "webuser:view", "ftauser:view"}, logical = Logical.OR)
    public FebsResponse updateStatus(User user) throws FebsException {
        try {
            if (user.getUserId() == null) {
                throw new FebsException("用户ID为空");
            }
            this.userService.updateStatus(user);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改用户失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @Log("上传签名")
    @PostMapping("uploadSign")
    @ResponseBody
    @RequiresPermissions(value = {"user:update", "webuser:view", "ftauser:view"}, logical = Logical.OR)
    public FebsResponse upload(@RequestParam("file") MultipartFile file) throws FebsException {

        try {
            log.info("file >> {}", file.getOriginalFilename());
            byte[] image = file.getBytes();
            String base64 = Base64.getEncoder().encodeToString(image);
            return new FebsResponse().success().data(base64);
        } catch (Exception e) {
            String message = "签名上传失败失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }


    private void setDefaultDept(User user) {
        if (StringUtils.isEmpty(user.getDeptId())) {
            //默认用自己的服务中心给新加的用户
            user.setDeptId(getCurrentUser().getDeptId());
        }
    }

    @PostMapping("password/reset/{userIds}")
    @RequiresPermissions(value = {"user:password:reset", "webuser:view", "ftauser:view"}, logical = Logical.OR)
    public FebsResponse resetPassword(@NotBlank(message = "{required}") @PathVariable String userIds) throws FebsException {
        try {
            String[] userIdArr = userIds.split(StringPool.COMMA);
            this.userService.resetPassword(userIdArr);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "重置用户密码失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @PostMapping("password/update")
    public FebsResponse updatePassword(
            @NotBlank(message = "{required}") String oldPassword,
            @NotBlank(message = "{required}") String newPassword) throws FebsException {
        try {
            User user = getCurrentUser();
            if (!StringUtils.equals(user.getPassword(), MD5Util.encrypt(user.getUserName(), oldPassword))) {
                return new FebsResponse().fail().message("原密码不正确");
            }
            userService.updatePassword(user.getUserName(), newPassword);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改密码失败，" + e.getMessage();
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("avatar/{image}")
    public FebsResponse updateAvatar(@NotBlank(message = "{required}") @PathVariable String image) throws FebsException {
        try {
            User user = getCurrentUser();
            this.userService.updateAvatar(user.getUserName(), image);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改头像失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @PostMapping("theme/update")
    public FebsResponse updateTheme(String theme, String isTab) throws FebsException {
        try {
            User user = getCurrentUser();
            this.userService.updateTheme(user.getUserName(), theme, isTab);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改系统配置失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @PostMapping("profile/update")
    public FebsResponse updateProfile(User user) throws FebsException {
        try {
            User currentUser = getCurrentUser();
            user.setUserId(currentUser.getUserId());
            this.userService.updateProfile(user);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改个人信息失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("excel")
    @RequiresPermissions("user:export")
    public void export(User user, HttpServletResponse response) throws FebsException {
        List<User> users = new ArrayList<>();
        try {
            if (hasHeadCompanyRole()) {
                //总公司用户权限
            } else {
                user.setDeptId(getCurrentUser().getDeptId());
            }
            users = this.userService.exportUsers(user);
            ExcelKit.$Export(User.class, response).downXlsx(users, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @GetMapping("excel4SignIn")
    @RequiresPermissions("user:export")
    public void export4SignIn(HttpServletResponse response) throws FebsException {
        List<User> users = new ArrayList<>();
        List<UserSignInDto> list = new ArrayList<>();
        try {
            User user = new User();
            if (hasHeadCompanyRole()) {
                //总公司用户权限
            } else {
                user.setDeptId(getCurrentUser().getDeptId());
            }
            users = this.userService.findUserList(user);
            if (!CollectionUtils.isEmpty(users)) {
                users.forEach(u -> {
                    UserSignInDto us = new UserSignInDto();
                    us.setUserName(u.getUname());
                    us.setUserNo(u.getUserNo());
                    list.add(us);
                });
            }
            ExcelKit.$Export(UserSignInDto.class, response).downXlsx(list, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }


    @GetMapping("userListByDeptId/{choosedId}")
    @RequiresPermissions("user:view")
    public FebsResponse userListByDeptId(@NotBlank(message = "{required}") @PathVariable String choosedId, User user, QueryRequest request) {
        if (choosedId != null && !"".equals(choosedId)) {
            user.setDeptId(choosedId);
        }
        Map<String, Object> dataTable = getDataTable(this.userService.findUserDetail(user, request));
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping("userListByParam/{retrieveParameter}")
    @RequiresPermissions("user:view")
    public FebsResponse userListByParam(@NotBlank(message = "{required}") @PathVariable String retrieveParameter, User user, QueryRequest request) {
        if (retrieveParameter != null && !"".equals(retrieveParameter)) {
            String[] arr = retrieveParameter.split(",", -2);
            String username = arr[0];
            String roleName = arr[1];
            if (username != null && !"".equals(username)) {
                user.setUserName(username);
            }
            if (roleName != null && !"".equals(roleName)) {
                Long roleId = this.userService.findRoleIdByRoleName(roleName);
                user.setRoleId(String.valueOf(roleId));
            }
        }
        Map<String, Object> dataTable = getDataTable(this.userService.findUserDetail(user, request));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 获取服务中心下拉菜单
     *
     * @author JHG
     * @date 2019-07-19 13:11:12
     */
    @GetMapping("dept/list")
    @ResponseBody
    public FebsResponse getAllDept(Dept dept, QueryRequest request) {
        return new FebsResponse().success().data(this.deptService.findDepts(dept, request));
    }

    /**
     * 获取部门下的user
     *
     * @param deptId
     * @author dinght
     * @date 2024-08-13 13:11:12
     */
    @GetMapping("deptUserList")
    @ResponseBody
    public FebsResponse deptUserList(String deptId) {
        return new FebsResponse().success().data(this.userService.deptUserList(deptId));
    }
}
